package org.example.test.thread_test.sort_test;


/**
 * 三个线程顺序打印数字
 */
public class SortThread {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadTest(0));
        Thread thread2 = new Thread(new ThreadTest(1));
        Thread thread3 = new Thread(new ThreadTest(2));
        thread1.start();
        thread2.start();
        thread3.start();
    }

    static class ThreadTest implements Runnable {
        //当前打印的数
        private static volatile int count = 0;

        //当前线程的标识
        private Integer index;

        private static final Object lock = new Object();

        public ThreadTest(Integer index) {
            this.index = index;
        }

        @Override
        public void run() {
            while (count < 100) {
                synchronized (lock) {
                    if (index != count % 3) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        if (count < 100) {
                            System.out.println("线程" + index + ",打印数字：" + count);
                        }
                        count++;
                        lock.notifyAll();
                    }
                }
            }
        }
    }
}
